package com.example.week9_advanceui;

import android.content.DialogInterface;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class StudentQuery_Activity extends AppCompatActivity {

    //定义内部对象
    ListView listView;
    StudentDBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_query_);
        //设置标题栏
        this.setTitle("浏览学生列表信息");

        //初始化组件
        listView=(ListView)findViewById(R.id.studentListview);

        //创建数据库对象
        dbHelper=new StudentDBHelper(this);

        //用自定义函数执行查询数据并显示结果（全体学生清单）
        use_cursor();

        //提示对话框，在下面的事件监听器中要调用
        final AlertDialog.Builder builder=new AlertDialog.Builder(this);

        //设置ListView单击监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //取得id
                final long temp=id;
                //设置对话框
                builder.setMessage("真的要删除该记录吗？").setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除数据
                        dbHelper.del((int) temp);
                        //再次查询并显示学生信息
                        use_cursor();
                    }
                })
               .setPositiveButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create();
                        builder.show();
            }
        });
      //关闭数据库
        dbHelper.close();
    }

    private void use_cursor()
    {
        //查询数据，获取游标
        Cursor cursor=dbHelper.query();
        Log.d("提示","有结果");
        //列表项数据
        String[] from={"_id","num","name"};
        //列表项ID
        int[] to={ R.id.student_id, R.id.student_num, R.id.student_name};

        //适配器
        SimpleCursorAdapter adapter=new SimpleCursorAdapter(getApplicationContext(),R.layout.studentrow,cursor,from,to);

        //为列表视图添加适配器
        listView.setAdapter(adapter);
    }

}
